<?php


namespace app\index\behavior;


use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use MongoDB\Driver\Exception\UnexpectedValueException;
use think\Request;


class CheckLogin {

    function actionBegin(){
        $req = \think\facade\Request::instance();
        $controller = $req->controller();
        if('Login'==$controller || 'User'==$controller){
            return;
        }
        @$token = $_SERVER['HTTP_X_TOKEN'];
        try{
            if(empty($token)){
                throw new \Exception("尚未登录");
            }
            $user=JWT::decode($token,config('jwt_key'),['HS256']);

        }catch (\Exception $e){
            $message='';
            if($e instanceof UnexpectedValueException || $e instanceof SignatureInvalidException){
                $message='token失效';
            }elseif($e instanceof ExpiredException){
                $message="登录超时";
            }else{
                $message=$e->getMessage();
            }
            header('Http/1.1 401');
            header('Content-Type:text/json;charset=UTF-8');
            echo $message;
            die;
        }
    }
}